/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import entities.Group;
import entities.User;
import java.security.Principal;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Alberto, Alessandra
 */
@Stateless
public class UserManager {

    @PersistenceContext
    EntityManager em;
    
    @Inject
    Principal principal;
   
    public void save(User user) {
        user.setCalendarvisibility(Boolean.TRUE);
        user.setGroupName(Group.USER);
        em.persist(user);
    }
    
    public Boolean checkUsername (String username) {
        try {
            em.createNamedQuery("findByUsername" , User.class)
                .setParameter("Uusername", username)
                .getSingleResult();
        } catch (NoResultException e) {
            return true;
        }
        return false;
    }
    
    public void modify (User user) {
        em.merge(user);
    }

    public void unregister() {
        em.remove(getLoggedUser());
    }

    public User getLoggedUser() {
        return em.createNamedQuery("findByUsername" , User.class)
            .setParameter("Uusername", principal.getName())
            .getSingleResult();
    }
}
